package com.hliushi.learn.service.impl;

import com.hliushi.learn.bean.Person;
import com.hliushi.learn.dao.PersonRepository;
import com.hliushi.learn.exception.BusinessErrorException;
import com.hliushi.learn.exception.BusinessMsgEnum;
import com.hliushi.learn.service.PersonService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author llhuang10
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonRepository personRepository;

    @Override
    public Person getPerson(String personId) {

        return personRepository.findById(personId).orElseThrow(() ->
                new BusinessErrorException(BusinessMsgEnum.UNEXCEPTION_EXCEPTION));
    }

    @Override
    public Person updatePerson(Person person) {
        if (StringUtils.isBlank(person.getPersonId())) {
            log.error("personId 参数不能为空");
            throw new BusinessErrorException(BusinessMsgEnum.PARAMETER_EXCEPTION);
        }

        // 更新用户
        personRepository.findById(person.getPersonId())
                .ifPresent(entity -> {
                    entity.setName(person.getName());
                    entity.setSex(person.getSex());
                });

        // 上面的那代码等同于下面4行
        Person person1 = personRepository.findById(person.getPersonId()).get();
        person1.setName(person.getName());
        person1.setSex(person.getSex());
        personRepository.save(person1);

        return person;
    }

    @Override
    public Person addPerson(Person person) {
        return personRepository.save(person);
    }

}
